<template>
  <div class="property-panel">
    <div v-if="designStore.canvasComponents.length > 0" class="panel-content">
      <!-- === 组件选择器 === -->
      <el-form label-position="left" label-width="100px" size="small">
        <el-form-item label="选中组件">
          <el-select 
            v-model="selectedComponentIdModel"
            placeholder="通过列表选择组件"
            clearable
            filterable
            style="width: 100%;" 
          >
            <el-option
              v-for="compInfo in designStore.allComponentsFlatList"
              :key="compInfo.id"
              :value="compInfo.id"
              :label="getComponentLabel(compInfo)"
            >
              <span :style="{ paddingLeft: `${compInfo.depth * 15}px` }">
                {{ getComponentLabel(compInfo) }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
       <!-- === 组件选择器结束 === -->

      <!-- 画布设置面板 -->
      <template v-if="isCanvasSelected">
        <div class="section-header">
          <h4>画布属性</h4>
        </div>
        <el-form label-position="left" label-width="100px" size="small">
          <el-form-item label="宽度">
            <div class="input-with-unit">
              <el-input-number
                v-model="canvasWidth"
                :min="100"
                controls-position="right"
                @change="updateCanvasSize"
              />
              <span class="unit-label">px</span>
            </div>
          </el-form-item>
          <el-form-item label="高度">
            <div class="input-with-unit">
              <el-input-number
                v-model="canvasHeight"
                :min="100"
                controls-position="right"
                @change="updateCanvasSize"
              />
              <span class="unit-label">px</span>
            </div>
          </el-form-item>
          <el-form-item label="背景颜色">
            <el-color-picker
              v-model="canvasBackgroundColor"
              show-alpha
              @change="updateCanvasStyle"
            />
          </el-form-item>
          <el-form-item label="边框宽度">
            <div class="input-with-unit">
              <el-input-number
                v-model="canvasBorderWidth"
                :min="0"
                controls-position="right"
                @change="updateCanvasStyle"
              />
              <span class="unit-label">px</span>
            </div>
          </el-form-item>
          <el-form-item label="边框样式">
            <el-select
              v-model="canvasBorderStyle"
              @change="updateCanvasStyle"
            >
              <el-option
                v-for="style in ['none', 'solid', 'dashed', 'dotted', 'double']"
                :key="style"
                :label="style"
                :value="style"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="边框颜色">
            <el-color-picker
              v-model="canvasBorderColor"
              show-alpha
              @change="updateCanvasStyle"
            />
          </el-form-item>
          <el-form-item label="圆角半径">
            <div class="input-with-unit">
              <el-input-number
                v-model="canvasBorderRadius"
                :min="0"
                controls-position="right"
                @change="updateCanvasStyle"
              />
              <span class="unit-label">px</span>
            </div>
          </el-form-item>
        </el-form>
      </template>

      <!-- 普通组件属性面板 -->
      <template v-else-if="selectedComponent">
          <div class="section-header">
            <h4>基础信息</h4>
            <el-tooltip content="删除组件" placement="top">
              <el-button
                type="danger"
                :icon="Delete"
                circle
                size="small"
                class="delete-button"
                @click="handleDeleteComponent"
              />
            </el-tooltip>
          </div>
          <el-form label-position="left" label-width="100px" size="small" :key="selectedComponent.id">
            <el-form-item label="ID">
              <el-input :value="selectedComponent.id" disabled />
            </el-form-item>
            <el-form-item label="类型">
              <el-input :value="selectedComponent.type" disabled />
            </el-form-item>
            <el-form-item label="组件名称">
              <el-input
                v-model="componentName"
                placeholder="(可选)"
                clearable
              />
            </el-form-item>
            <el-form-item label="可见性">
               <el-switch 
                 v-model="componentVisible" />
            </el-form-item>
             <el-form-item label="层级">
                <el-input-number
                  v-model="componentZIndex"
                  controls-position="right"
                  :min="0"
                  step-strictly
                />
            </el-form-item>
          </el-form>

          <!-- 库组件专用编辑器 -->
          <component 
            v-if="isLibraryComponent && getLibraryEditorComponentName"
            :is="getLibraryEditorComponentName"
            :datas="componentDatas"
            :data-type="selectedComponent.type"
          />

          <template v-else-if="filteredComponentConfig.length > 0">
            <div class="section-header" v-if="hasStyleProps">
              <h4>样式属性</h4>
            </div>
            <el-form label-position="left" label-width="100px" size="small">
              <template v-for="config in filteredComponentConfig" :key="`${config.category}-${config.key}`">
                <el-form-item :label="config.label" v-if="!config.key.includes('hidden')">
                  <div class="input-with-unit" v-if="config.editor === 'number' && config.key !== 'zIndex' && !['modelValue', 'max', 'min', 'step', 'percentage'].includes(config.key)">
                    <component
                      :is="editorComponentMap[config.editor]"
                      :model-value="getPropertyValue(config.key, config.category)"
                      @update:model-value="(val: any) => updatePropertyValue(config.key, config.category, val, config.editor)"
                      v-bind="getEditorProps(config)"
                    />
                    <span class="unit-label">px</span>
                  </div>
                  <component
                    v-else
                    :is="editorComponentMap[config.editor]"
                    :model-value="getPropertyValue(config.key, config.category)"
                    @update:model-value="(val: any) => updatePropertyValue(config.key, config.category, val, config.editor)"
                    v-bind="getEditorProps(config)"
                  >
                    <template v-if="config.editor === 'select' && config.options">
                        <el-option
                            v-for="option in config.options"
                            :key="typeof option === 'string' ? option : option.value"
                            :label="typeof option === 'string' ? option : option.label"
                            :value="typeof option === 'string' ? option : option.value"
                        />
                    </template>
                  </component>
                </el-form-item>
              </template>
            </el-form>
          </template>

          <OptionsEditor 
            v-if="hasOptionsToManage"
            :component-id="selectedComponent.id"
          />

          <SelectOptionsEditor 
            v-if="hasSelectOptions"
            :component-id="selectedComponent.id"
          />

          <TableColumnsEditor 
            v-if="hasTableColumns"
            :component-id="selectedComponent.id"
          />

          <p v-if="filteredComponentConfig.length === 0 && !hasOptionsToManage && !hasSelectOptions && !hasTableColumns">此组件暂无 Style/Props/Options 配置项。</p>

      </template>
       <div v-else class="placeholder">
           <p>通过上方列表或点击画布选择组件</p>
       </div>

    </div>
    <div v-else class="placeholder">
      <p>画布上还没有组件</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, watch, ref, shallowRef } from 'vue';
import { useDesignStore, type ComponentInfo } from '@/stores/designStore';
import { getComponentConfig, editorComponentMap, type PropertyConfig } from '@/config/propertyPanelConfig';
import { Delete } from '@element-plus/icons-vue';
import OptionsEditor from './OptionsEditor.vue';
import SelectOptionsEditor from './SelectOptionsEditor.vue';
import TableColumnsEditor from './TableColumnsEditor.vue';

const designStore: ReturnType<typeof useDesignStore> = useDesignStore();

// 判断是否选中了画布
const isCanvasSelected = computed(() => designStore.selectedComponentId === 'canvas');

// 获取当前选中组件
const selectedComponent = computed(() => designStore.selectedComponent);

// 判断当前选中的是否为库组件
const isLibraryComponent = computed(() => {
  if (!selectedComponent.value) return false;
  return selectedComponent.value.type.startsWith('ew-');
});

// 动态计算库组件编辑器名称的计算属性
const getLibraryEditorComponentName = computed(() => {
  if (!isLibraryComponent.value || !selectedComponent.value) return null;
  
  // 获取基础组件名（去掉ew-前缀）
  const baseComponentName = selectedComponent.value.type.replace('ew-', '');
  // 编辑器组件名称为：{组件名}style（按照README.md规范）
  const editorComponentName = `${baseComponentName}style`;
  console.log(`[RightPanel] 使用库组件编辑器: ${editorComponentName}`);
  
  return editorComponentName;
});

// 画布属性
const canvasWidth = ref(designStore.canvasSize.width);
const canvasHeight = ref(designStore.canvasSize.height);
const canvasBackgroundColor = ref('#ffffff');
const canvasBorderWidth = ref(1);
const canvasBorderStyle = ref('solid');
const canvasBorderColor = ref('#cccccc');
const canvasBorderRadius = ref(4);

// 更新画布尺寸
const updateCanvasSize = () => {
  designStore.updateCanvasSize({
    width: canvasWidth.value,
    height: canvasHeight.value
  });
  console.log(`[RightPanel] 更新画布尺寸: ${canvasWidth.value}x${canvasHeight.value}`);
};

// 更新画布样式
const updateCanvasStyle = () => {
  // 找到画布元素并设置样式
  const canvasElement = document.querySelector('.canvas-content') as HTMLElement;
  if (canvasElement) {
    canvasElement.style.backgroundColor = canvasBackgroundColor.value;
    canvasElement.style.borderWidth = `${canvasBorderWidth.value}px`;
    canvasElement.style.borderStyle = canvasBorderStyle.value;
    canvasElement.style.borderColor = canvasBorderColor.value;
    canvasElement.style.borderRadius = `${canvasBorderRadius.value}px`;
    console.log('[RightPanel] 更新画布样式');
  }
};

// 监视选择的组件变化，初始化画布属性值
watch(() => designStore.selectedComponentId, (newVal) => {
  if (newVal === 'canvas') {
    // 获取当前画布元素的样式
    const canvasElement = document.querySelector('.canvas-content') as HTMLElement;
    if (canvasElement) {
      // 同步画布尺寸到输入框
      canvasWidth.value = designStore.canvasSize.width;
      canvasHeight.value = designStore.canvasSize.height;
      
      // 获取计算后的样式
      const computedStyle = window.getComputedStyle(canvasElement);
      canvasBackgroundColor.value = computedStyle.backgroundColor || '#ffffff';
      canvasBorderWidth.value = parseInt(computedStyle.borderWidth || '1');
      canvasBorderStyle.value = computedStyle.borderStyle || 'solid';
      canvasBorderColor.value = computedStyle.borderColor || '#cccccc';
      canvasBorderRadius.value = parseInt(computedStyle.borderRadius || '4');
    }
  }
});

const rawComponentConfig = computed<PropertyConfig[]>(() => {
  if (!selectedComponent.value) return [];
  return getComponentConfig(selectedComponent.value.type);
});

const filteredComponentConfig = computed<PropertyConfig[]>(() => {
    const baseKeys = ['name', 'visible', 'zIndex'];
    return rawComponentConfig.value.filter(config => 
        !baseKeys.includes(config.key) && 
        !(config.key === 'children' && config.hasOptions)
    );
});

// 添加计算属性来检查是否有样式属性
const hasStyleProps = computed(() => {
  return filteredComponentConfig.value.some(config => config.category === 'style');
});

const hasOptionsToManage = computed<boolean>(() => {
  if (!selectedComponent.value) return false;
  return rawComponentConfig.value.some(config => config.key === 'children' && config.hasOptions);
});

const hasSelectOptions = computed<boolean>(() => {
  if (!selectedComponent.value) return false;
  return selectedComponent.value.type === 'el-select';
});

const hasTableColumns = computed<boolean>(() => {
  if (!selectedComponent.value) return false;
  return selectedComponent.value.type === 'el-table';
});

const getPropertyValue = (key: string, category: 'style' | 'props' | 'root') => {
  if (!selectedComponent.value) return undefined;
  
  if (category === 'root') {
      if (key === 'visible') {
          return selectedComponent.value.visible !== false;
      }
      return selectedComponent.value[key as keyof typeof selectedComponent.value];
  }
  
  const target = category === 'style' ? selectedComponent.value.style : selectedComponent.value.props;
  if (!target) return undefined;

  const config = rawComponentConfig.value.find(c => c.key === key && c.category === category);
  
  if (config?.editor === 'number' && typeof target[key] === 'string' && target[key].endsWith('px')) {
      return parseFloat(target[key]) || 0;
  }
  
  // 处理评分组件的modelValue等数值型属性
  if (key === 'modelValue' && config?.editor === 'number' && target[key] !== undefined) {
    return typeof target[key] === 'string' ? parseFloat(target[key]) : target[key];
  }
  
  if (key === 'zIndex' && target[key] === undefined) {
      return undefined;
  }

  return target[key];
};

const updatePropertyValue = (key: string, category: 'style' | 'props' | 'root', value: any, editorType?: PropertyConfig['editor']) => {
  if (!selectedComponent.value) return;
  const componentId = selectedComponent.value.id;

  let finalValue = value;
  if (editorType === 'number') {
      const isPxProperty = !['modelValue', 'max', 'min', 'step', 'percentage', 'zIndex'].includes(key);
      
      if (key === 'zIndex') {
          finalValue = (value === null || value === undefined || value === '') ? undefined : Number(value);
      } else if (isPxProperty) {
          finalValue = (value === null || value === undefined || value === '') ? undefined : `${Number(value)}px`;
      } else {
          // 对于评分组件的modelValue等，保持数值类型
          finalValue = (value === null || value === undefined || value === '') ? undefined : Number(value);
      }
  } else if (editorType === 'color' && value === null) {
      finalValue = '';
  } else if (editorType === 'switch' && key === 'visible') {
      finalValue = !!value;
  }

  console.log(`Updating ${category}.${key} for ${componentId} with value:`, finalValue);

  if (category === 'root') {
    designStore.updateComponentRootProps(componentId, { [key]: finalValue });
  } else if (category === 'style') {
    designStore.updateComponentStyle(componentId, { [key]: finalValue });
  } else if (category === 'props') {
    designStore.updateComponentProps(componentId, { [key]: finalValue });
  } else {
      console.warn('Unknown property category:', category);
  }
};

const getEditorProps = (config: PropertyConfig) => {
    const editorProps: Record<string, any> = {};
    if (config.editor === 'number') {
        if (config.min !== undefined) editorProps.min = config.min;
        if (config.max !== undefined) editorProps.max = config.max;
        if (config.step !== undefined) editorProps.step = config.step;
        editorProps.controlsPosition = 'right';
    }
    if (config.editor === 'select') {
        editorProps.clearable = true;
    }
    if (config.editor === 'color') {
        editorProps.showAlpha = true;
    }
    return editorProps;
};

let lastCategoryRendered = '';
const shouldShowCategoryHeader = (category: string, config: PropertyConfig): boolean => {
    if (category === 'root') return false; 
    const configIndex = filteredComponentConfig.value.findIndex(c => c.key === config.key && c.category === config.category);
    const show = configIndex === 0 || filteredComponentConfig.value[configIndex - 1]?.category !== category;
    return show;
};
const getCategoryLabel = (category: 'style' | 'props' | 'root'): string => {
    if (category === 'style') return '样式属性 (Style)';
    if (category === 'props') return '组件属性 (Props)';
    return category;
};

const handleDeleteComponent = () => {
    if (designStore.selectedComponentId) {
        console.log(`属性面板：点击删除按钮，删除组件 ${designStore.selectedComponentId}`);
        designStore.deleteComponent(designStore.selectedComponentId);
    }
};

const componentName = computed<string>({
  get: () => selectedComponent.value?.name ?? '',
  set: (value: string) => {
    if (selectedComponent.value) {
      designStore.updateComponentRootProps(selectedComponent.value.id, { name: value });
    }
  }
});

const componentVisible = computed<boolean>({
  get: () => selectedComponent.value?.visible ?? true,
  set: (value: boolean) => {
    if (selectedComponent.value) {
      designStore.updateComponentRootProps(selectedComponent.value.id, { visible: value });
    }
  }
});

const componentZIndex = computed<number>({
  get: () => {
    const zIndex = selectedComponent.value?.style?.zIndex;
    const parsed = typeof zIndex === 'string' ? parseInt(zIndex, 10) : zIndex;
    return typeof parsed === 'number' && !isNaN(parsed) ? parsed : 0;
  },
  set: (value: number | null | undefined) => {
    if (selectedComponent.value) {
      const newZIndex = (typeof value === 'number' && !isNaN(value) && value >= 0) ? value : 0;
       console.log(`Updating zIndex for ${selectedComponent.value.id} to:`, newZIndex);
      designStore.updateComponentStyle(selectedComponent.value.id, { zIndex: newZIndex });
    }
  }
});

// v-model for the component selector dropdown
const selectedComponentIdModel = computed<string>({
    get: () => designStore.selectedComponentId || '',
    set: (id) => {
        console.log('Select dropdown changed selection to:', id);
        designStore.selectComponent(id || null);
    }
});

// Helper function to format the label for the dropdown option
const getComponentLabel = (compInfo: ComponentInfo): string => {
    const namePart = compInfo.name ? `${compInfo.name} (${compInfo.type})` : `未命名 (${compInfo.type})`;
    // return `${namePart} - ${compInfo.id.substring(compInfo.id.length - 8)}`; // Show last 8 chars of ID
    // --- 修改下面这行 ---
    const idPart = compInfo.id.substring(compInfo.id.length - 8);
    const hiddenMarker = compInfo.visible === false ? ' [隐藏]' : ''; // 添加这行
    return `${namePart} - ${idPart}${hiddenMarker}`; // 修改这行
};

// 添加计算属性获取当前组件的datas数据
const componentDatas = computed(() => {
  if (!selectedComponent.value || !selectedComponent.value.props) {
    return {};
  }
  // 确保datas存在
  if (!selectedComponent.value.props.datas) {
    // 初始化datas对象
    designStore.updateComponentProps(selectedComponent.value.id, {
      datas: {}
    });
    return {};
  }
  return selectedComponent.value.props.datas;
});

</script>

<style scoped>
.property-panel {
  width: 350px;
  height: 100%;
  overflow-y: auto;
  padding: 15px;
}

.panel-content h4 {
  margin-top: 20px;
  margin-bottom: 10px;
  font-size: 14px;
  color: #303133;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}
.panel-content h4:first-child {
  margin-top: 0;
}

.el-form-item {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

:deep(.el-input-number),
:deep(.el-select),
:deep(.el-input) {
    width: 100%;
}

.unit-label {
  margin-left: 5px;
  color: #909399;
  font-size: 12px;
}

.placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    margin-bottom: 15px;
}
.section-header h4 {
    margin: 0;
    border-bottom: none;
    padding-bottom: 0;
}
.section-header:first-of-type {
    margin-top: 0;
}

:deep(.el-switch) {
  margin-right: auto; /* 让switch靠左对齐 */
}

:deep(.el-color-picker) {
  width: auto !important;
}

:deep(.el-color-picker__trigger) {
  width: 36px !important;
  height: 36px !important;
}

.delete-button {
    /* 微调按钮位置 */
}

.input-with-unit {
  display: flex;
  align-items: center;
  width: 100%;
}

.input-with-unit :deep(.el-input-number),
.input-with-unit :deep(.el-input) {
  flex: 1;
}
</style> 